﻿using CCWin;
using ERP_SaaS_WinForm.登录.Common;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Windows.Forms;

namespace ERP_SaaS_WinForm
{
    public partial class LoginForm : CCSkinMain
    {
        public LoginForm()
        {
            InitializeComponent();
            this.txtUserName.Focus();//聚焦用户名输入框

            // 确保密码框设置为密码模式
            SetPasswordMode();
            
            // 添加键盘事件处理
            this.KeyPreview = true;
            this.KeyDown += LoginForm_KeyDown;
            
            // 设置窗体样式
            SetupFormStyles();
            
            // 加载保存的登录信息
            LoadSavedLoginInfo();
            
            // 窗体加载完成后再次确保密码模式
            this.Load += LoginForm_Load;
            this.Shown += LoginForm_Shown;
            
            // 监听密码框文本变化，确保始终显示为密码字符
            this.txtPwd.TextChanged += TxtPwd_TextChanged;
            
            // 设置窗体图标
            SetFormIcon();
            
            // 使用定时器确保密码模式在窗体完全显示后生效
            Timer initTimer = new Timer();
            initTimer.Interval = 500;
            initTimer.Tick += (s, e) => {
                SetPasswordMode();
                initTimer.Stop();
                initTimer.Dispose();
            };
            initTimer.Start();
        }

        private void LoginForm_Load(object sender, EventArgs e)
        {
            // 窗体加载完成后再次设置密码模式
            SetPasswordMode();
        }

        private void LoginForm_Shown(object sender, EventArgs e)
        {
            // 窗体显示后再次设置密码模式
            SetPasswordMode();
        }

        private void TxtPwd_TextChanged(object sender, EventArgs e)
        {
            // 每次文本变化时都确保密码模式
            SetPasswordMode();
        }

        private void LoginForm_KeyDown(object sender, KeyEventArgs e)
        {
            // Ctrl+P 切换密码显示/隐藏
            if (e.Control && e.KeyCode == Keys.P)
            {
                TogglePasswordVisibility();
                e.Handled = true;
            }
        }

        private void SetPasswordMode()
        {
            try
            {
                // 确保密码框设置为密码模式
                this.txtPwd.IsPasswordChat = '●';
                this.txtPwd.IsSystemPasswordChar = false; // 不使用系统密码字符，使用自定义的●
                
                // 如果SkinTxt存在，也设置其密码模式
                if (this.txtPwd.SkinTxt != null)
                {
                    this.txtPwd.SkinTxt.PasswordChar = '●';
                    this.txtPwd.SkinTxt.UseSystemPasswordChar = false;
                }
                
                // 强制刷新显示
                this.txtPwd.Invalidate();
                if (this.txtPwd.SkinTxt != null)
                {
                    this.txtPwd.SkinTxt.Invalidate();
                }
                
                // 使用定时器延迟设置，确保界面完全加载后再次设置
                Timer timer = new Timer();
                timer.Interval = 100;
                timer.Tick += (s, e) => {
                    try
                    {
                        this.txtPwd.IsPasswordChat = '●';
                        this.txtPwd.IsSystemPasswordChar = false;
                        if (this.txtPwd.SkinTxt != null)
                        {
                            this.txtPwd.SkinTxt.PasswordChar = '●';
                            this.txtPwd.SkinTxt.UseSystemPasswordChar = false;
                        }
                        this.txtPwd.Invalidate();
                        if (this.txtPwd.SkinTxt != null)
                        {
                            this.txtPwd.SkinTxt.Invalidate();
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"延迟设置密码模式失败: {ex.Message}");
                    }
                    finally
                    {
                        timer.Stop();
                        timer.Dispose();
                    }
                };
                timer.Start();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"设置密码模式失败: {ex.Message}");
            }
        }

        private void SetFormIcon()
        {
            try
            {
                // 尝试多个可能的路径
                string[] possiblePaths = {
                    Path.Combine(Application.StartupPath, "..", "..", "Images", "w.ico")
                };
                
                string iconPath = null;
                foreach (string path in possiblePaths)
                {
                    Console.WriteLine($"检查路径: {path}");
                    if (File.Exists(path))
                    {
                        iconPath = path;
                        Console.WriteLine($"找到图标文件: {path}");
                        break;
                    }
                }
                
                if (iconPath != null)
                {
                    Console.WriteLine("正在加载图标...");
                    this.Icon = new System.Drawing.Icon(iconPath);
                    Console.WriteLine("图标加载成功！");
                }
                else
                {
                    Console.WriteLine("图标文件不存在，创建默认图标...");
                    // 如果找不到w.ico文件，创建一个简单的默认图标
                    CreateDefaultIcon();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"设置窗体图标失败: {ex.Message}");
            }
        }

        private void CreateDefaultIcon()
        {
            try
            {
                // 创建一个简单的默认图标
                using (Bitmap bmp = new Bitmap(32, 32))
                using (Graphics g = Graphics.FromImage(bmp))
                {
                    // 绘制一个简单的图标
                    g.Clear(Color.FromArgb(41, 128, 185)); // 使用主题蓝色
                    
                    // 绘制一个简单的锁图标
                    using (Pen pen = new Pen(Color.White, 2))
                    using (SolidBrush brush = new SolidBrush(Color.White))
                    {
                        // 绘制锁的主体
                        g.FillRectangle(brush, 8, 16, 16, 12);
                        g.DrawRectangle(pen, 8, 16, 16, 12);
                        
                        // 绘制锁的顶部
                        g.FillEllipse(brush, 10, 12, 12, 8);
                        g.DrawEllipse(pen, 10, 12, 12, 8);
                        
                        // 绘制钥匙孔
                        g.FillEllipse(brush, 14, 20, 4, 4);
                    }
                    
                    // 保存为临时图标文件
                    string tempIconPath = Path.Combine(Application.StartupPath, "temp_icon.ico");
                    bmp.Save(tempIconPath, System.Drawing.Imaging.ImageFormat.Icon);
                    this.Icon = new System.Drawing.Icon(tempIconPath);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"创建默认图标失败: {ex.Message}");
            }
        }

        private void SetupFormStyles()
        {
            // 设置登录卡片样式
            panelLoginCard.Region = System.Drawing.Region.FromHrgn(CreateRoundRectRgn(0, 0, panelLoginCard.Width, panelLoginCard.Height, 15, 15));
            
            // 设置按钮样式
            btnSubmit.Region = System.Drawing.Region.FromHrgn(CreateRoundRectRgn(0, 0, btnSubmit.Width, btnSubmit.Height, 8, 8));
        }

        [System.Runtime.InteropServices.DllImport("Gdi32.dll")]
        private static extern IntPtr CreateRoundRectRgn(int nLeftRect, int nTopRect, int nRightRect, int nBottomRect, int nWidthEllipse, int nHeightEllipse);

        private void panelBackground_Paint(object sender, PaintEventArgs e)
        {
            // 绘制背景渐变效果
            using (LinearGradientBrush brush = new LinearGradientBrush(
                panelBackground.ClientRectangle,
                Color.FromArgb(25, 42, 86),
                Color.FromArgb(41, 128, 185),
                LinearGradientMode.Vertical))
            {
                e.Graphics.FillRectangle(brush, panelBackground.ClientRectangle);
            }

            // 绘制装饰性圆点
            using (SolidBrush dotBrush = new SolidBrush(Color.FromArgb(100, 255, 255, 255)))
            {
                Random rand = new Random(123); // 固定种子以确保一致性
                for (int i = 0; i < 50; i++)
                {
                    int x = rand.Next(0, panelBackground.Width);
                    int y = rand.Next(0, panelBackground.Height);
                    int size = rand.Next(2, 6);
                    e.Graphics.FillEllipse(dotBrush, x, y, size, size);
                }
            }
        }

        private void LoadSavedLoginInfo()
        {
            try
            {
                string configFile = Path.Combine(Application.StartupPath, "login_config.txt");
                if (File.Exists(configFile))
                {
                    string[] lines = File.ReadAllLines(configFile);
                    if (lines.Length >= 3)
                    {
                        bool rememberPassword = bool.Parse(lines[0]);
                        if (rememberPassword)
                        {
                            txtUserName.Text = lines[1];
                            txtPwd.Text = lines[2];
                            chkRememberPassword.Checked = true;
                            
                            // 重新设置密码模式
                            SetPasswordMode();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // 如果加载失败，忽略错误
                Console.WriteLine($"加载保存的登录信息失败: {ex.Message}");
            }
        }

        private void SaveLoginInfo()
        {
            try
            {
                string configFile = Path.Combine(Application.StartupPath, "login_config.txt");
                
                if (chkRememberPassword.Checked)
                {
                    // 保存登录信息
                    string[] lines = {
                        "true",
                        txtUserName.Text.Trim(),
                        txtPwd.Text.Trim()
                    };
                    File.WriteAllLines(configFile, lines);
                }
                else
                {
                    // 清除保存的登录信息
                    if (File.Exists(configFile))
                    {
                        File.Delete(configFile);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"保存登录信息失败: {ex.Message}");
            }
        }

        private void ShowAlert(string message,string caption)
        {
            MessageBox.Show(message, caption, MessageBoxButtons.OK, caption == "成功" ? MessageBoxIcon.Information
                : caption == "提示" ? MessageBoxIcon.Information
                : MessageBoxIcon.Error);
        }

        private async void btnSubmit_Click(object sender, EventArgs e)
        {
            string Name = txtUserName.Text.Trim();
            string Password = txtPwd.Text.Trim();

            if (string.IsNullOrEmpty(Name) || string.IsNullOrEmpty(Password))
            {
                ShowAlert("请输入用户名和密码", "提示");
                return;
            }

            try
            {
                var body = new { Name = Name, Password = Password };
                var json = JsonConvert.SerializeObject(body);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                {
                    var http = HttpClientProvider.Client;

                    var resp = await http.PostAsync("http://10.223.8.23:8009/api/Account/Login", content);
                    var respText = await resp.Content.ReadAsStringAsync();

                    // 调试：显示后端返回的原始数据
                    Console.WriteLine($"后端返回数据: {respText}");

                    if (!resp.IsSuccessStatusCode)
                    {
                        ShowAlert($"HTTP错误: {resp.StatusCode}", "错误");
                        return;
                    }

                    var apiResult = JsonConvert.DeserializeObject<APIResult<LoginUserDto>>(respText);
                    if (apiResult == null)
                    {
                        ShowAlert("服务器响应格式错误", "错误");
                        return;
                    }

                    var data = apiResult.Data;
                    if (apiResult.Code == (int)ResultCode.Success && data != null)
                    {
                        TokenDto.JwtToken = data.Token ?? string.Empty;
                        TokenDto.Name = Name;
                        TokenDto.Password = Password;

                        // 将JWT设置到全局HttpClient的Authorization头部
                        HttpClientProvider.SetJwtToken(TokenDto.JwtToken);

                        // 构建成功消息
                        string successMessage = apiResult.Message;
                        if (string.IsNullOrEmpty(successMessage))
                        {
                            successMessage = $"欢迎 {Name}，登录成功！";
                        }
                        else if (!successMessage.Contains("成功"))
                        {
                            successMessage = $"欢迎 {Name}，{successMessage}";
                        }
                        
                        // 保存登录信息（如果勾选了记住密码）
                        SaveLoginInfo();
                        
                        ShowAlert(successMessage, "成功");

                        // 登录成功后打开主页面
                        this.Hide(); // 隐藏登录窗体
                        var mainForm = new ERP_SaaS_WinForm.显示.MainForm();
                        mainForm.ShowDialog();
                        this.Close(); // 关闭登录窗体
                    }
                    else
                    {
                        ShowAlert(apiResult.Message ?? "登录失败", "失败");
                    }
                }
            }
            catch (JsonException ex)
            {
                ShowAlert($"JSON解析错误: {ex.Message}", "错误");
            }
            catch (HttpRequestException ex)
            {
                ShowAlert($"网络连接错误: {ex.Message}", "错误");
            }
            catch (Exception ex)
            {
                ShowAlert($"登录异常: {ex.Message}", "错误");
            }
        }



        /// <summary>
        /// 切换密码显示/隐藏
        /// </summary>
        private void TogglePasswordVisibility()
        {
            if (this.txtPwd.IsPasswordChat == '●')
            {
                // 当前是隐藏状态，切换到显示状态
                this.txtPwd.IsPasswordChat = '\0';
                this.txtPwd.IsSystemPasswordChar = false;
                if (this.txtPwd.SkinTxt != null)
                {
                    this.txtPwd.SkinTxt.PasswordChar = '\0';
                    this.txtPwd.SkinTxt.UseSystemPasswordChar = false;
                }
                ShowAlert("密码已显示", "提示");
            }
            else
            {
                // 当前是显示状态，切换到隐藏状态
                this.txtPwd.IsPasswordChat = '●';
                this.txtPwd.IsSystemPasswordChar = false; // 不使用系统密码字符
                if (this.txtPwd.SkinTxt != null)
                {
                    this.txtPwd.SkinTxt.PasswordChar = '●';
                    this.txtPwd.SkinTxt.UseSystemPasswordChar = false;
                }
                ShowAlert("密码已隐藏", "提示");
            }
            
            // 强制刷新显示
            this.txtPwd.Invalidate();
            if (this.txtPwd.SkinTxt != null)
            {
                this.txtPwd.SkinTxt.Invalidate();
            }
        }


    }
}
